<?php
/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-08-22
 * Time: 22:11
 */

namespace plugin\csauto\app\process;


use plugin\csauto\app\model\TorrentListModel;
use plugin\csauto\app\service\RssWorkService;
use support\Log;
use Workerman\Crontab\Crontab;
use Workerman\Timer;

/**
 * Class RssAssignTaskProcess
 * 步骤1
 * 通过RSS进行订阅检查
 *
 * @package plugin\csauto\app\process
 */
class RssAssignTaskProcess
{
    // 定时器句柄/ID
    protected $timer;
    protected $wechatTimer;

    // 时间间隔 (单位: 秒, 默认5秒)
    protected $interval = 300;
    protected $maxTask = 20;

    public function onWorkerStart()
    {
        if (getenv('WORK_DEBUG')) return true;
        $this->timer = Timer::add($this->interval, function () {
            try {
                // 这里执行系统预设的定时任务事件
                $this->run();
            } catch (\Throwable $e) {
                echo 'ERROR[RssAssignTaskProcess]: ' . $e->getMessage() . PHP_EOL;
            }
        });

        return true;
    }

    public function run()
    {
        addlog('RSS订阅检查', 'start');
        $tNum = TorrentListModel::where('torrents_status', 1)->count();
        addlog('RssAssignTaskProcess', "当前待分配任务数量：{$tNum}，最大上限：{$this->maxTask}");
        // 无论是否超出数量，都进行RSS查询
        RssWorkService::requestRssList(RssWorkService::rssList());
        
        // 查询后检查任务数量，如果超出最大上限，将最早的记录标记为失效
        $newTNum = TorrentListModel::where('torrents_status', 1)->count();
        if (intval($newTNum) > intval($this->maxTask)) {
            $excessCount = intval($newTNum) - intval($this->maxTask);
            addlog('RssAssignTaskProcess', "超出最大上限，需要标记失效数量：{$excessCount}");
            
            // 获取最早创建的记录，标记为失效状态(99)
            $oldestRecords = TorrentListModel::where('torrents_status', 1)
                ->orderBy('created_at', 'asc')
                ->limit($excessCount)
                ->select();
            
            foreach ($oldestRecords as $record) {
                $record->torrents_status = 99;
                $record->save();
                addlog('RssAssignTaskProcess', "标记失效：种子ID={$record->torrent_id}，标题={$record->torrent_title}");
            }
        }
        
        return '任务调用：' . date('Y-m-d H:i:s') . "\n";
    }

    /**
     * 停止/删除定时器
     *
     * @return bool
     */
    public function stop()
    {
        return Timer::del($this->timer);
    }

}